import time
from datetime import date

import grpc
from loguru import logger
from peewee import DoesNotExist
from user_srv.model.models import User
from user_srv.proto import user_pb2, user_pb2_grpc


class UserServicer(user_pb2_grpc.UserServicer):

    def convert_user_to_resp(self, user):
        user_info_rsp = user_pb2.UserInfoResponse()
        user_info_rsp.id = user.id
        user_info_rsp.password = user.password
        user_info_rsp.mobile = user.mobile
        user_info_rsp.role = user.role
        if user.nick_name:
            user_info_rsp.nickName = user.nick_name
        if user.gender:
            user_info_rsp.gender = user.gender
        if user.birthday:
            user_info_rsp.birthday = int(time.mktime(user.birthday.timetuple()))

        return user_info_rsp

    @logger.catch
    def GetUserList(self, request: user_pb2.PageInfo, context):
        # 获取用户列表信息
        rsp = user_pb2.UserListResponse()
        # logger.debug("调用GetUserList")
        users = User.select()
        rsp.total = users.count()

        start = 0;
        page = 1
        per_page_numbers = 10
        if request.pSize:
            per_page_numbers = request.pSize
        if request.pn:
            page = request.pn
            start = per_page_numbers * (page - 1)

        users = users.limit(per_page_numbers).offset(start)
        for user in users:
            rsp.data.append(self.convert_user_to_resp(user))

        return rsp

    @logger.catch
    def GetUserById(self, request: user_pb2.IdRequest, context):
        try:
            # user = User.select().where(User.id == request.id)
            # return self.convert_user_to_resp(user[0])
            user = User.get(User.id == request.id)
            return self.convert_user_to_resp(user)
        except DoesNotExist as e:
            context.set_code(grpc.StatusCode.NOT_FOUND)
            context.set_details("用户不存在")
            return user_pb2.UserInfoResponse()

    @logger.catch
    def GetUserByMobile(self, request: user_pb2.MobileRequest, context):
        try:
            user = User.select()
            user = user.where(User.mobile == request.mobile).get()
            return self.convert_user_to_resp(user)
        except DoesNotExist as e:
            context.set_code(grpc.StatusCode.NOT_FOUND)
            context.set_details("用户不存在")
            return user_pb2.UserInfoResponse()
